package com.ruoyi.order.utils;

import com.ruoyi.order.service.ITbOrderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.kafka.core.KafkaTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * 分表分库存储选择工具类
 *
 * @author 12692
 */
public class DivisionUtil {
    @Resource
    ITbOrderService tbOrderService;
    @Resource
    RedissonClient redisson;
    @Resource
    KafkaTemplate<String, String> kafkaTemplate;
    public void DivisionTOThreeTable(String tbOrder){
        RLock lock = redisson.getLock("lock::orderId");
        try {
            // 尝试获取锁
            boolean tryLock = lock.tryLock(5, 30, TimeUnit.SECONDS);
            if( tryLock ){
                // 添加锁成功 执行操作
                try {
                    int total = tbOrderService.getAllOrderListNumber();
                    int i = total % 3;
                    if( i == 0 ){
                        kafkaTemplate.send("TableOne",tbOrder);
                    } else if( i == 1 ){
                        kafkaTemplate.send("TableTow",tbOrder);
                    } else if( i == 2 ){
                        kafkaTemplate.send("TableThree",tbOrder);
                    }
                }finally {
                    // 执行完毕之后释放锁
                    lock.unlock();
                }
            }
        } catch (Exception e){
            // 处理中断异常
            Thread.currentThread().interrupt();
        }
    }
}
